package com.jereh.topnews.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jereh.topnews.entity.Channel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/25.
 */
public class ChannelDao {

//    private DBHelper helper;
    private SQLiteDatabase db;
    private DBUtils dbUtils;

    public ChannelDao(Context ctx) {
//        helper=DBHelper.getDbHelper(ctx);
        //返回一个可以读写的数据库对象
//        db=helper.getDb();
        dbUtils=new DBUtils(ctx);
        db=dbUtils.getDatabase();
    }

    /**
     * 添加所有频道数据
     * @param list
     */
    public void addAll(List<Channel> list) {
        //开启一个事务
        db.beginTransaction();
        for(int i=0;i<list.size();i++) {
            db.execSQL("insert into channel values (null,?,?)",new Object[]{list.get(i).getChannelId(),list.get(i).getName()});
        }
        //执行事务
        db.setTransactionSuccessful();
        //关闭事务
        db.endTransaction();
    }

    /**
     * 查询所有频道数据
     * @return
     */
    public List<Channel> findAll() {
        List<Channel> list=new ArrayList<>();
        Cursor cursor=db.rawQuery("select * from channel",null);
        while (cursor.moveToNext()) {
            Channel channel=new Channel(cursor.getString(cursor.getColumnIndex("channelId")),cursor.getString(cursor.getColumnIndex("name")));
            //把id放进去
            channel.setId(cursor.getInt(cursor.getColumnIndex("id")));
            list.add(channel);
        }
        return list;
    }

    /**
     * 查询数据的条数
     * @return
     */
    public int count() {
        int count=0;
        Cursor cursor=db.rawQuery("select count(id) as count from channel",null);
        while (cursor.moveToNext()) {
            count=cursor.getInt(cursor.getColumnIndex("count"));
        }
        return count;
    }

    public void closeDB() {
        if(db.isOpen()) {
            db.close();
        }
    }

}
